package com.valuegroup.smarttodo.ui.todo.habit;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.HabitOrder;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.plugins.ClickableTextView;
import com.valuegroup.smarttodo.plugins.MultilineEditText;
import com.valuegroup.smarttodo.plugins.pickdialog.DatePickDialog;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.plugins.pickdialog.OnCustomSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.OnSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.bean.DateType;
import com.valuegroup.smarttodo.util.AlertUtils;

import java.util.Date;

import androidx.annotation.Nullable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import mehdi.sakout.fancybuttons.FancyButton;

/**
 * 习惯清单表单
 * 用于习惯清单的添加与编辑
 */
public class HabitOrderSetActivity extends BaseActivity {

    @BindView(R.id.btnBack)
    ImageButton btnBack;
    @BindView(R.id.btnSave)
    TextView btnSave;
    @BindView(R.id.labTitle)
    ClickableTextView labTitle;
    @BindView(R.id.labTitleEdit)
    MultilineEditText labTitleEdit;

    @BindView(R.id.labStartDt)
    TextView labStartDt;
    @BindView(R.id.labEndDt)
    TextView labEndDt;
    @BindView(R.id.btnChoiceStartDt)
    LinearLayout btnChoiceStartDt;
    @BindView(R.id.btnChoiceEndDt)
    LinearLayout btnChoiceEndDt;
    @BindView(R.id.checkRepeat)
    Switch checkRepeat;
    @BindView(R.id.btnChoicePreMinute)
    LinearLayout btnChoicePreMinute;
    @BindView(R.id.labMinute)
    TextView labMinute;
    @BindView(R.id.labHeaderTitle)
    TextView labHeaderTitle;
    @BindView(R.id.btnDel)
    FancyButton btnDel;

    private Long DATA_ID;
    private Integer DATA_POSITION;
    private HabitOrder DATA;
    boolean doDel = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_habitorder_set);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    private void initData() {

        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        DATA_POSITION = getIntent().getIntExtra(PARAMS_POSITION, 0);
        DATA = ServiceFactory.getInstance().getHabitService().getHabitOrderDao().load(DATA_ID);

        if (DATA_ID != 0 && DATA == null) {
            AlertUtils.showToast(getApplicationContext(), R.string.not_found_record);
            finish();
            return;
        }

        if (DATA_ID == 0) {
            DATA = ServiceFactory.getInstance().getHabitService().getDefaultHabitOrder();
            DATA.setTitle(null);

            // 新增状态需要屏蔽删除按钮
            btnDel.setVisibility(View.GONE);
        }

        labTitle.setText(DATA.getTitle());
        labStartDt.setText(DateUtils.date2str(DATA.getStartTime(), DateUtils.F21));
        labEndDt.setText(DateUtils.date2str(DATA.getEndTime(), DateUtils.F21));
        checkRepeat.setChecked(DATA.getOpenRemind());
        labMinute.setText(String.format(getResources().getString(R.string.lab_minute), DATA.getRemindInterval()));
    }

    private void initView() {
        // 任务主干编辑状态控制
        labTitleEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    labTitleEdit.setVisibility(View.GONE);
                    labTitle.setText(v.getText());
                    labTitle.setVisibility(View.VISIBLE);
                }
                // 返回true，保留软键盘。false，隐藏软键盘
                return true;
            }
        });

        labTitleEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    // 得到焦点

                    // 光标移动到末尾
                    labTitleEdit.setSelection(labTitleEdit.getText().length());

                    // 弹出键盘
                    InputMethodManager inputManager = (InputMethodManager) labTitleEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(labTitleEdit, 0);
                } else {
                    // 失去焦点
                    labTitleEdit.setVisibility(View.GONE);
                    labTitle.setText(labTitleEdit.getText());
                    labTitle.setVisibility(View.VISIBLE);
                }
            }
        });

        checkRepeat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                DATA.setOpenRemind(isChecked);
            }
        });

    }

    @OnClick({R.id.btnBack, R.id.btnSave, R.id.btnChoiceStartDt, R.id.btnChoiceEndDt, R.id.btnChoicePreMinute, R.id.labTitle, R.id.btnDel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnDel:
                AlertUtils.delOrderDialog(view.getContext(),
                        String.format(getResources().getString(R.string.alt_del_habit_join), DATA.getTitle()),
                        (dialog, which) -> {
                            ServiceFactory.getInstance().getHabitService().delHabitOrder(DATA.getId());

                            // 跳转至习惯列表
                            doDel = true;
                            setCloseParams();
                            finishAfterTransition();
                        });
                break;
            case R.id.btnBack:
                // 返回事件
                setCloseParams();
                finishAfterTransition();
                break;
            case R.id.btnSave:
                // 保存事件
                if (labTitle.getText().length() == 0) {
                    AlertUtils.showToast(view.getContext(), R.string.not_inset_content);
                    return;
                }
                if (DATA.getId() == null && ServiceFactory.getInstance().getHabitService().existOrderName(labTitle.getText().toString())) {
                    AlertUtils.showToast(view.getContext(), R.string.exist_content);
                    return;
                }


                DATA.setTitle(labTitle.getText().toString());
                ServiceFactory.getInstance().getHabitService().saveHabitOrder(DATA);
                if (DATA_ID != 0) {
                    setCloseParams();
                }
                finishAfterTransition();
                break;
            case R.id.btnChoiceStartDt:
                doDatePickDialog(true);
                break;
            case R.id.btnChoiceEndDt:
                doDatePickDialog(false);
                break;
            case R.id.btnChoicePreMinute:

                DatePickDialog d5 = new DatePickDialog(this);
                d5.setType(DateType.TYPE_CUSTOM_MINUTE_INTERVAL_5);
                d5.setStartData(DATA.getRemindInterval());
                d5.setOnCustomSureLisener(new OnCustomSureLisener() {
                    @Override
                    public void onSure(Object obj) {
                        DATA.setRemindInterval((int) obj);
                        labMinute.setText(String.format(getResources().getString(R.string.lab_minute), DATA.getRemindInterval()));
                    }
                });
                d5.show();

                break;
            case R.id.labTitle:

                labTitle.setVisibility(View.GONE);

                labTitleEdit.setText(labTitle.getText());
                labTitleEdit.setVisibility(View.VISIBLE);

                // 获得焦点
                labTitleEdit.setFocusable(true);
                labTitleEdit.setFocusableInTouchMode(true);
                labTitleEdit.requestFocus();
                break;
        }
    }

    private void doDatePickDialog(final boolean isStart) {
        DatePickDialog d = new DatePickDialog(this);
        d.setType(DateType.TYPE_HM);
        d.setStartDate(isStart ? DATA.getStartTime() : DATA.getEndTime());
        d.setOnSureLisener(new OnSureLisener() {
            @Override
            public void onSure(Date date) {
                String hour = DateUtils.date2str(date, DateType.TYPE_HM.getFormat());
                if (isStart) {
                    DATA.setStartTime(date);
                    labStartDt.setText(hour);
                } else {
                    DATA.setEndTime(date);
                    labEndDt.setText(hour);
                }
            }
        });
        d.show();
    }


    @Override
    public void onBackPressed() {
        setCloseParams();
        super.onBackPressed();
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        intent.putExtra(PARAMS_POSITION, DATA_POSITION);
        intent.putExtra(PARAMS_KEY, DATA_ID);
        intent.putExtra(DEL_TAG, doDel);
        setResult(RESULT_OK, intent);
    }
}
